<template>
	<view class="article-container">
		<!-- 文章详情 -->
		<view class="article-content">
			<!-- 作者信息 -->
			<view class="author-info">
				<image class="avatar" src="/static/images/avatar-xiaoxin.png" mode="widthFix"></image>
				<view class="author-meta">
					<view class="author-name">{{form.createBy}}</view>
					<view class="publish-time">{{form.createTime}}</view>
				</view>
			</view>

			<!-- 文章内容（此处根据实际数据渲染，示例用占位符） -->
			<view class="content">
				<!-- 实际项目中通过接口获取文章内容，支持富文本 -->
				<rich-text :nodes="form.broadcastContent"></rich-text>
			</view>
			<view>
				<ImagePreview :src="form.img"></ImagePreview>
			</view>

			<!-- 文章操作区 -->
			<view class="article-actions" style="margin-top: 25rpx;">
				<view class="action-item" @click="share">
					<uni-icons type="redo" size="20" color="#666"></uni-icons>
					<text class="action-text">分享</text>
				</view>
				<view class="action-item" @click="handleLike">
					<uni-icons type="heart" :color="likeForm.status=='1'?'#ff4d4f' : '#666'" size="20"></uni-icons>
					<text class="action-text"
						:style="likeForm.status=='1'? 'color: #ff4d4f' : ''">{{ form.likeNum }}</text>
				</view>
				<view class="action-item" @click="handleCollect">
					<uni-icons type="star" :color="favForm.status=='1' ? '#ffd100' : '#666'" size="20"></uni-icons>
					<text class="action-text">{{ form.favNum }}</text>
				</view>
			</view>
		</view>

		<!-- 评论区 -->
		<view class="comment-section">
			<view class="comment-header">
				<text class="comment-title">评论 · {{ commentCount }}</text>
			</view>

			<!-- 评论列表 -->
			<view class="comment-list">
				<view class="comment-item" v-for="(comment, index) in commentList" :key="index"
					style="position: relative;">
					<!-- 评论者信息 -->
					<view class="comment-author">
						<image class="comment-avatar" :src="comment.avatar" mode="widthFix"></image>
						<view class="comment-meta">
							<view class="comment-name">{{ comment.userName }}</view>
							<view class="comment-time">{{ comment.evaluationTime }}</view>
							<view class="comment-location" v-if="comment.city">{{ comment.city }}</view>
						</view>
					</view>

					<!-- 评论内容 -->
					<view class="comment-content">{{ comment.content }}</view>

					<!-- 评论操作 -->
					<view class="comment-actions">
						<view class="comment-action" @click="handleCommentLike(comment)">
							<uni-icons type="heart" :color="comment.isLiked ? '#ff4d4f' : '#666'" size="16"></uni-icons>
							<text class="action-text">{{ comment.likeCount }}</text>
						</view>
						<view class="comment-action" @click="showReplyInput(comment)">
							<uni-icons type="chatbubble" size="16" color="#666"></uni-icons>
							<text class="action-text">回复</text>
						</view>

					</view>
					<view class="reply-input" v-if="comment.showReplyInput" style="position: absolute;">
						<input type="text" v-model="replyContent" placeholder="输入回复内容..." class="reply-input-field">
						</input>
						<button class="reply-submit" @click="submitReply(comment)">发送</button>
					</view>
					<!-- 回复列表 -->
					<view class="reply-list" v-if="comment.children && comment.children.length > 0">
						<view class="reply-item" v-for="(reply, rIndex) in comment.children" :key="rIndex">
							<view class="reply-content">
								<text class="reply-author">{{ reply.userName }}：</text>
								<text>{{ reply.content }}</text>
							</view>
							<view class="reply-actions">
								<text class="reply-time">{{ reply.createTime }}</text>
								<view>
									<text class="reply-like" @click="handleReplyLike(comment, reply)">
										<uni-icons type="heart" :color="reply.isLiked ? '#ff4d4f' : '#666'"
											size="14"></uni-icons>
										<text>5</text>
									</text>
									<text style="margin-left: 18rpx;" @click="showReplyInput(reply)">
										<uni-icons type="chatbubble" size="16" color="#666"></uni-icons>
										<text>回复2</text>
									</text>
								</view>

							</view>
							<view class="reply-input" v-if="reply.showReplyInput">

								<input type="text" v-model="replyContent" placeholder="输入回复内容..."
									class="reply-input-field">
								</input>
								<button class="reply-submit" @click="submitReply(reply)">发送1</button>
							</view>
						</view>
					</view>

					<!-- 回复输入框（点击回复时显示） -->
					<!-- <view class="reply-input" v-if="comment.showReplyInput">
						<input type="text" v-model="comment.replyContent" placeholder="输入回复内容..."
							class="reply-input-field">
						</input>
						<button class="reply-submit" @click="submitReply(comment)">发送</button>
					</view> -->
				</view>
			</view>

			<!-- 评论输入框 -->
			<view class="add-comment">
				<input type="text" v-model="newComment" placeholder="写下你的评论..." class="comment-input"></input>
				<button class="comment-submit" @click="submitComment">发布</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getDynamicBroadcast
	} from '@/common/api/dynamicBroadcast.js'
	import {
		addLike,
		deleteLike
	} from '@/common/api/dynamicBroadcastLikes.js'
	import {
		addFav
	} from '@/common/api/dynamicBroadcastFav.js'
	import {
		addEvaluate,
		listDynamicBroadcastEvaluate
	} from '@/common/api/dynamicBroadcastEvaluate.js'
	import ImagePreview from '@/components/ImagePreview.vue'
	import AMapLoader from "@amap/amap-jsapi-loader";
	import {
		securityJsCode,
		key
	} from '@/config/env.js'
	export default {
		data() {
			return {
				id: null,
				form: {},
				likeForm: {}, //点赞信息
				favForm: {}, //收藏信息
				replyContent: '', //回复的内容
				showFabu: true, //发布评论是否显示
				// likeCount: 10, // 点赞数
				isLiked: false, // 是否点赞
				collectCount: 1, // 收藏数
				isCollected: false, // 是否收藏
				commentCount: 11, // 评论总数
				curentLongitude: null,
				curentLatitude: null,
				// 评论列表数据
				commentList: [{
						id: 1,
						author: '小美',
						avatar: '/static/images/avatar-xiaomei.png',
						time: '03-08',
						location: '河北石家庄',
						content: '这篇动态很有价值！',
						likeCount: 5,
						isLiked: false,
						showReplyInput: false, // 是否显示回复输入框
						replyContent: '', // 回复内容
						children: [{
							replier: '小新',
							content: '谢谢支持！',
							time: '03-08 15:00',
							likeCount: 2,
							isLiked: false
						}]
					}
					// 可添加更多评论...
				],

				// 新评论内容
				newComment: ''
			};
		},
		onLoad(option) {
			//this.getCurrentLatLon();
			this.id = option.id
			this.getDetail();
			this.listEvaluate()

		},
		components: {
			ImagePreview
		},
		methods: {
			// 返回上一页
			navigateBack() {
				uni.navigateBack({
					delta: 1
				});
			},
			listEvaluate() {
				listDynamicBroadcastEvaluate({
					dynamicBroadcastId: this.id
				}).then((res) => {
					console.log(res)
					debugger
					this.commentList = res.data

				})
			},
			getCurrentLatLon() {

				// alert("初始化地图")
				//alert(curentLongitude.value, curentLatitude.value)
				window._AMapSecurityConfig = {
					securityJsCode: securityJsCode,
				};
				// alert("1")
				console.log("1..............")
				AMapLoader.load({
						key: key, // 申请好的Web端开发者Key，首次调用 load 时必填
						version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
						plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
					})
					.then((AMap) => {
						// alert("2")
						console.log("2..............")
						AMap.plugin('AMap.Geolocation', () => {
							var geolocation = new AMap.Geolocation({
								enableHighAccuracy: true, //是否使用高精度定位，默认:true
								timeout: 10000, //超过10秒后停止定位，默认：5s
								position: 'RB', //定位按钮的停靠位置
								offset: [10, 20], //定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
								zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点

							});


							// this.map.addControl(geolocation);
							geolocation.getCurrentPosition((status, result) => {
								// alert("3")
								console.log("3..............")
								if (status == 'complete') {
									// alert("获取成功")
									// alert("4")
									console.log("4..............")
									var startLonLat = JSON.parse(JSON.stringify(result.position))
									this.curentLongitude = startLonLat[0]
									this.curentLatitude = startLonLat[1]



								} else {
									// alert("5")
									console.log("5..............")


								}
							});
						});

					})
					.catch((e) => {
						// alert("3")
						alert(e);
					});
			},
			share() {
				uni.share({
					provider: "weixin",
					scene: "WXSceneTimeline",
					type: 2,
					imageUrl: "https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/uni@2x.png",
					success: function(res) {
						console.log("success:" + JSON.stringify(res));
					},
					fail: function(err) {
						console.log("fail:" + JSON.stringify(err));
					}
				});
			},
			getDetail() {
				getDynamicBroadcast(this.id).then((res) => {
					if (res.code == 200) {
						this.form = res.data
						this.likeForm = res.data.likeInfo
						this.favForm = res.data.favInfo
						this.isCollected = res.data.likeInfo.status == '1' ? true : false
						this.isLiked = res.data.likeInfo.status == '1' ? true : false
					}

				})
			},
			// 处理分享
			handleShare() {
				uni.showActionSheet({
					itemList: ['分享到微信', '分享到朋友圈', '分享到QQ'],
					success: (res) => {
						console.log('选择了第', res.tapIndex, '项');
						// 调用分享API
					}
				});
			},

			// 处理点赞
			handleLike() {

				this.likeForm.status = this.likeForm.status == '1' ? '0' : '1'

				if (this.likeForm.id && this.isLiked) { //曾经点过赞，现在取消点赞
					console.log("111111111")
					this.form.likeNum--;
					//调用后台接口，删除点赞信息,把id设置为空
					this.setLikeData()
				}
				if (this.likeForm.id && !this.isLiked) { //取消了点过赞，现在点赞
					console.log("111111111")
					this.form.likeNum--;
					//调用后台接口，删除点赞信息,把id设置为空
					this.setLikeData()
				} else if (!this.likeForm.id && this.likeForm.status == '1') {
					console.log("22222")
					this.form.likeNum++;
					//新增点赞信息
					this.setLikeData()
				} else if (!this.likeForm.id && this.likeForm.status == '0') {
					console.log("3333")
					this.form.likeNum--;

				}
			},
			//设置点赞数据
			setLikeData() {
				uni.showLoading({
					title: '请稍等'
				});
				addLike({
					...this.likeForm,
					dynamicBroadcastId: this.form.id
				}).then((res) => {
					uni.hideLoading()
					this.likeForm.id = res.data

					if (res.data != null) {
						uni.showToast({
							title: '已点赞',
							icon: 'none',
							duration: 2000
						});
					} else {
						uni.showToast({
							title: '已取消点赞',
							icon: 'none',
							duration: 2000
						});
					}

				})

			},

			// 处理收藏
			handleCollect() {
				this.favForm.status = this.favForm.status == '1' ? '0' : '1'

				if (this.favForm.id && this.isCollected) { //曾经点过赞，现在取消点赞
					console.log("111111111")
					this.form.favNum--;
					//调用后台接口，删除点赞信息,把id设置为空
					this.setFavData()
				}
				if (this.favForm.id && !this.isCollected) { //取消了点过赞，现在点赞
					console.log("111111111")
					this.form.favNum--;
					//调用后台接口，删除点赞信息,把id设置为空
					this.setFavData()
				} else if (!this.favForm.id && this.favForm.status == '1') {
					console.log("22222")
					this.form.favNum++;
					//新增点赞信息
					this.setFavData()
				} else if (!this.favForm.id && this.favForm.status == '0') {
					console.log("3333")
					this.form.favNum--;

				}
			},
			//设置点赞数据
			setFavData() {
				uni.showLoading({
					title: '请稍等'
				});
				addFav({
					...this.favForm,
					dynamicBroadcastId: this.form.id
				}).then((res) => {
					uni.hideLoading()
					this.favForm.id = res.data

					if (res.data != null) {
						uni.showToast({
							title: '已点赞',
							icon: 'none',
							duration: 2000
						});
					} else {
						uni.showToast({
							title: '已取消点赞',
							icon: 'none',
							duration: 2000
						});
					}

				})

			},

			// 显示回复输入框
			showReplyInput(comment) {
				this.showFabu = false
				// 关闭其他评论的回复输入框
				this.closeReplay(this.commentList, comment)
				// 切换当前评论的回复输入框显示状态
				comment.showReplyInput = !comment.showReplyInput;

			},
			closeReplay(list, comment) {

				list.forEach(item => {
					if (item.id !== comment.id) {
						item.showReplyInput = false;

					}
					if (item.children && item.children.length > 0) {
						this.closeReplay(item.children, comment)
					}
				});
			},
			// 提交回复
			submitReply(comment) {

				if (!this.replyContent.trim()) {
					uni.showToast({
						title: '回复内容不能为空',
						icon: 'none'
					});
					return;
				}
				let form = {
					content: this.replyContent,
					parentId: comment.id,
					ancestors: comment.ancestors + "," + comment.id,
					dynamicBroadcastId: this.id,
					level: comment.level + 1,
					longitude: this.curentLongitude,
					latitude: this.curentLatitude
				}
				addEvaluate(form).then((res) => {
					if (res.code == 200) {
						uni.showToast({
							title: '已回复',
							icon: "none",
							duration: 2000
						});
						if (comment.children == null) {
							comment.children = []
						}
						comment.children.push(res.data)
						this.replyContent = '';
						comment.showReplyInput = false;
						this.showFabu = true
					}
				})

			},

			// 评论点赞
			handleCommentLike(comment) {
				comment.isLiked = !comment.isLiked;
				comment.likeCount += comment.isLiked ? 1 : -1;
				// 实际项目中调用评论点赞接口
			},

			// 回复点赞
			handleReplyLike(comment, reply) {
				reply.isLiked = !reply.isLiked;
				reply.likeCount += reply.isLiked ? 1 : -1;
				// 实际项目中调用回复点赞接口
			},

			// 提交评论
			submitComment() {
				if (!this.newComment.trim()) {
					uni.showToast({
						title: '评论内容不能为空',
						icon: 'none'
					});
					return;
				}
				// 模拟添加评论
				// this.commentList.unshift({
				// 	id: Date.now(), // 用时间戳作为临时ID
				// 	author: '我',
				// 	avatar: '/static/images/avatar-current.png',
				// 	time: this.getFormattedTime().split(' ')[0], // 只显示日期
				// 	location: '当前城市', // 实际项目中获取定位
				// 	content: this.newComment,
				// 	likeCount: 0,
				// 	isLiked: false,
				// 	showReplyInput: false,
				// 	replyContent: '',
				// 	replies: []
				// });

				let form = {
					content: this.newComment,
					parentId: 0,
					ancestors: '0',
					dynamicBroadcastId: this.id,
					level: 0,
					longitude: this.curentLongitude,
					latitude: this.curentLatitude
				}
				addEvaluate(form).then((res) => {
					if (res.code == 200) {
						uni.showToast({
							title: '已评论',
							icon: "none",
							duration: 2000
						});
						this.commentList.push(res.data)
						this.newComment = '';
					}
				})


			},

			// 获取格式化时间（如：03-09 16:30）
			getFormattedTime() {
				const date = new Date();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				return `${month}-${day} ${hours}:${minutes}`;
			}
		},


	};
</script>

<style scoped lang="scss">
	.article-container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	/* 导航栏 */
	.navbar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 44px;
		background-color: #007aff;
		padding: 0 16px;
	}

	.title {
		color: #fff;
		font-size: 18px;
		font-weight: 500;
	}

	/* 文章内容区 */
	.article-content {
		background-color: #fff;
		padding: 16px;
		margin-bottom: 10px;
	}

	.author-info {
		display: flex;
		align-items: center;
		margin-bottom: 16px;
	}

	.avatar {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		margin-right: 10px;
	}

	.author-name {
		font-size: 16px;
		font-weight: 500;
		margin-bottom: 4px;
	}

	.publish-time {
		font-size: 12px;
		color: #999;
	}

	.content {
		margin-bottom: 12px;
		line-height: 1.6;
	}

	/* 文章操作区 */
	.article-actions {
		display: flex;
		justify-content: space-around;
		padding: 10px 0;
		border-top: 1px solid #eee;
	}

	.action-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		color: #666;
	}

	.action-text {
		font-size: 12px;
		margin-top: 4px;
	}

	/* 评论区 */
	.comment-section {
		background-color: #fff;
		padding: 16px;
	}

	.comment-header {
		margin-bottom: 16px;
		padding-bottom: 10px;
		border-bottom: 1px solid #eee;
	}

	.comment-title {
		font-size: 16px;
		font-weight: 500;
	}

	/* 评论列表 */
	.comment-list {
		margin-bottom: 20px;
	}

	.comment-item {
		padding: 10px 0;
		border-bottom: 1px solid #f5f5f5;
	}

	.comment-avatar {
		width: 36px;
		height: 36px;
		border-radius: 50%;
		margin-right: 10px;
	}

	.comment-meta {
		flex: 1;
	}

	.comment-name {
		font-size: 14px;
		font-weight: 500;
		margin-bottom: 2px;
	}

	.comment-time,
	.comment-location {
		font-size: 11px;
		color: #999;
		display: inline-block;
		margin-right: 10px;
	}

	.comment-content {
		margin: 8px 0 10px 46px;
		/* 与头像对齐 */
		font-size: 14px;
		color: #333;
	}

	.comment-actions {
		display: flex;
		margin-left: 46px;
		margin-bottom: 10px;
	}

	.comment-action {
		display: flex;
		align-items: center;
		margin-right: 20px;
		font-size: 12px;
		color: #666;
	}

	/* 回复列表 */
	.reply-list {
		margin-left: 46px;
		background-color: #f9f9f9;
		padding: 8px;
		border-radius: 4px;
		margin-bottom: 10px;
	}

	.reply-item {
		margin-bottom: 8px;
		font-size: 13px;
	}

	.reply-author {
		color: #007aff;
		font-weight: 500;
	}

	.reply-actions {
		display: flex;
		justify-content: space-between;
		margin-top: 4px;
		font-size: 11px;
		color: #999;
	}

	/* 回复输入框 */
	.reply-input {
		// position: absolute;
		display: flex;
		background-color: #fff;
		bottom: -22px;
		z-index: 999;
		width: 100%;
	}

	.reply-input-field {
		flex: 1;
		height: 36px;
		border: 1px solid #eee;
		border-radius: 18px;
		padding: 0 16px;
		font-size: 13px;
	}

	.reply-submit {
		width: 60px;
		height: 36px;
		line-height: 36px;
		text-align: center;
		background-color: #007aff;
		color: #fff;
		border-radius: 18px;
		font-size: 14px;
		margin-left: 8px;
	}

	/* 评论输入框 */
	.add-comment {

		background-color: #fff;
		width: 100%;
		bottom: 1rpx;
		display: flex;
		padding: 10px 0;
	}

	.comment-input {
		flex: 1;
		height: 40px;
		border: 1px solid #eee;
		border-radius: 20px;
		padding: 0 16px;
		font-size: 14px;
	}

	.comment-submit {
		width: 70px;
		height: 40px;
		line-height: 40px;
		text-align: center;
		background-color: #007aff;
		color: #fff;
		border-radius: 20px;
		font-size: 14px;
		margin-left: 10px;
	}
</style>